// svg更换颜色
export function changeSvgColor(url, color) {
	//转义后的#等于%23，利用正则表达式，替换所有%23后6位为新的十六进制六位数。
	let res = url.replace(/%22%23[a-zA-Z0-9]{3,6}/g, color.replace("#", "%22%23"))
	return res
}

// 全局工具函数

// 格式化日期
export function formatDate(date, format = 'YYYY-MM-DD') {
  if (!date) return '';
  
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hour = String(d.getHours()).padStart(2, '0');
  const minute = String(d.getMinutes()).padStart(2, '0');
  const second = String(d.getSeconds()).padStart(2, '0');
  
  return format
    .replace('YYYY', year)
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hour)
    .replace('mm', minute)
    .replace('ss', second);
}

// 格式化金额
export function formatMoney(amount, decimals = 2) {
  if (!amount && amount !== 0) return '0.00';
  
  const num = parseFloat(amount);
  if (isNaN(num)) return '0.00';
  
  return num.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// 获取文件扩展名
export function getFileExtension(filename) {
  if (!filename) return '';
  return filename.split('.').pop().toLowerCase();
}

// 检查文件类型
export function checkFileType(filename, allowedTypes = ['jpg', 'jpeg', 'png', 'gif']) {
  const ext = getFileExtension(filename);
  return allowedTypes.includes(ext);
}

// 压缩图片
export function compressImage(filePath, quality = 0.8) {
  return new Promise((resolve, reject) => {
    uni.compressImage({
      src: filePath,
      quality: quality * 100,
      success: (res) => {
        resolve(res.tempFilePath);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 获取设备信息
export function getDeviceInfo() {
  return new Promise((resolve) => {
    uni.getSystemInfo({
      success: (res) => {
        resolve(res);
      },
      fail: () => {
        resolve({});
      }
    });
  });
}

// 检查网络状态
export function checkNetworkStatus() {
  return new Promise((resolve) => {
    uni.getNetworkType({
      success: (res) => {
        resolve(res.networkType);
      },
      fail: () => {
        resolve('unknown');
      }
    });
  });
}

// 显示加载提示
export function showLoading(title = '加载中...') {
  uni.showLoading({
    title,
    mask: true
  });
}

// 隐藏加载提示
export function hideLoading() {
  uni.hideLoading();
}

// 显示成功提示
export function showSuccess(title = '操作成功', duration = 1500) {
  uni.showToast({
    title,
    icon: 'success',
    duration
  });
}

// 显示错误提示
export function showError(title = '操作失败', duration = 1500) {
  uni.showToast({
    title,
    icon: 'none',
    duration
  });
}

// 显示确认对话框
export function showConfirm(title, content) {
  return new Promise((resolve) => {
    uni.showModal({
      title,
      content,
      success: (res) => {
        resolve(res.confirm);
      },
      fail: () => {
        resolve(false);
      }
    });
  });
}

// 防抖函数
export function debounce(func, wait = 300) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// 节流函数
export function throttle(func, limit = 300) {
  let inThrottle;
  return function() {
    const args = arguments;
    const context = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// 深拷贝
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj.getTime());
  if (obj instanceof Array) return obj.map(item => deepClone(item));
  if (typeof obj === 'object') {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
}

// 生成随机ID
export function generateId(length = 8) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
}

// 验证手机号
export function validatePhone(phone) {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
}

// 验证邮箱
export function validateEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

// 验证身份证号
export function validateIdCard(idCard) {
  const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return idCardRegex.test(idCard);
}

// 获取用户信息
export function getUserInfo() {
  try {
    const userInfo = uni.getStorageSync('user-info');
    return userInfo || null;
  } catch (e) {
    return null;
  }
}

// 获取用户角色
export function getUserRole() {
  try {
    const role = uni.getStorageSync('user-role');
    return role || 1; // 默认销售角色
  } catch (e) {
    return 1;
  }
}

// 检查权限
export function checkPermission(permission) {
  const role = getUserRole();
  const userInfo = getUserInfo();
  
  if (!userInfo) return false;
  
  // 经理拥有所有权限
  if (role === 4) return true;
  
  // 根据角色检查具体权限
  const rolePermissions = {
    1: ['customer:read', 'customer:write', 'follow:read', 'follow:write'],
    2: ['finance:read', 'finance:write', 'payment:read', 'payment:write'],
    3: ['production:read', 'production:write', 'production:complete']
  };
  
  const permissions = rolePermissions[role] || [];
  return permissions.includes(permission);
}